#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace hcc;

const uint16_t glocalport = 8888;
const int gsockfd = -1;
enum 
{
    SOCKET_ERROR=1,
    BIND_ERROR
};
class UdpServer
{
public:
    UdpServer(uint16_t localport = glocalport)
        : _localport(localport),
          _sockfd(gsockfd),
          _isrunning(false)
    {
    }
    void InitServer()
    {
        // 1.创建套接字 fd
        _sockfd=::socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd<0)
        {
            LOG(INFO,"创建套接字失败\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG,"socket create success , _sockfd: %d\n",_sockfd);


        // 2.绑定
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_localport);
        local.sin_addr.s_addr=INADDR_ANY;
        int n=::bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG,"socket bind success \n");
    }
    void Start()
    {
        _isrunning=true;
        char inbuffer[1024];
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            ssize_t n=recvfrom(_sockfd,inbuffer,sizeof(inbuffer)-1,0,(struct sockaddr*)&peer,&len);
            if(n>0)
            {
                InetAddr addr(peer);
                inbuffer[n]=0;
                std::cout<<"[ "<<addr.Ip()<<" : "<<addr.Port()<<" ] : "<<inbuffer<<std::endl;

                std::string echo_string ="udp_server echo] # ";
                echo_string+=inbuffer;
                sendto(_sockfd,echo_string.c_str(),echo_string.size(),0,(struct sockaddr*)&peer,len);
            }
            else
            {
                LOG(INFO,"recvfrom error\n"); 
            }
        }
    }
    ~UdpServer()
    {
        if(gsockfd<_sockfd) ::close(_sockfd);
    }
private:
    int _sockfd;
    uint16_t _localport;
    // std::string _localip;
    bool _isrunning;
};